package com.bestcem.xm.survey.grpc.client;

import com.alibaba.fastjson.JSONObject;
import com.bestcem.xm.common.core.constant.GrpcClientNames;
import com.bestcem.xm.component.cache.annotation.XmCache;
import com.bestcem.xm.member.grpc.v1.enums.MemberTypeEnum;
import com.bestcem.xm.member.grpc.v1.services.*;
import com.bestcem.xm.survey.convert.grpc.SurveyGrpcConvertMapper;
import com.bestcem.xm.survey.grpc.client.dto.MemberDto;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Component
public class MemberGrpcClient {

    @GrpcClient(GrpcClientNames.DS_MEMBER)
    private MemberServiceGrpc.MemberServiceBlockingStub stub;

    private final com.bestcem.xm.survey.convert.grpc.SurveyGrpcConvertMapper surveyGrpcConvertMapper;

    public MemberGrpcClient(SurveyGrpcConvertMapper surveyGrpcConvertMapper) {
        this.surveyGrpcConvertMapper = surveyGrpcConvertMapper;
    }

    public List<MemberDto> ListMembersByParam(String orgId, Integer mtype, String field) {
        ListMembersByParamRequest.Builder builder = ListMembersByParamRequest.newBuilder();
        JSONObject newjson = new JSONObject();
        newjson.put("orgId", orgId);
        newjson.put("mtype", mtype);
        builder.setParam(String.valueOf(newjson));
        try {
            ListMembersByParamResponse response = stub.listMembersByParam(builder.build());
            if (Objects.isNull(response) || response.getStatus().getCodeValue() != 0) {
                log.error("[survey] ListMembersByParam error, orgId: {} mtype: {}", orgId, mtype);
                return Collections.emptyList();
            }
            return response.getMembersList().stream().map(surveyGrpcConvertMapper::toMemberDto).collect(Collectors.toList());
        } catch (Exception e) {
            log.error("[survey] ListMembersByParam exp error, orgId: {} mtype: {}", orgId, mtype);
            return Collections.emptyList();
        }
    }

    @XmCache
    public MemberDto getMemberById(String id) {
        GetMemberRequest.Builder builder = GetMemberRequest.newBuilder();
        builder.setId(id);
        try {
            GetMemberResponse response = stub.getMember(builder.build());
            if (Objects.isNull(response) || response.getStatus().getCodeValue() != 0) {
                log.error("[survey] getMemberById {} Error; ErrorMsg: {}", id, response);
                return null;
            }
            com.bestcem.xm.member.grpc.v1.common.Member member = response.getMember();
            return surveyGrpcConvertMapper.toMemberDto(member);
        } catch (Exception e) {
            log.error("[survey] getMemberById {} Error; ErrorMsg: {}", id, e.getMessage(), e);
            return null;
        }
    }

    public boolean checkDisplayRangePermission(String orgId, String userId, String memberId) {
        CheckDisplayRangePermissionRequest.Builder builder = CheckDisplayRangePermissionRequest.newBuilder();
        builder.setOrgId(orgId);
        builder.setUserId(userId);
        builder.setMemberId(memberId);
        try {
            CheckDisplayRangePermissionResponse response = stub.checkDisplayRangePermission(builder.build());
            if (response.getStatus().getCodeValue() != 0) {
                return false;
            }
            return response.getValid();
        } catch (Exception e) {
            log.error("[survey] ex checkDisplayRangePermission, memberId = {}, Error; ErrorMsg: {}", memberId, e.getMessage());
            return false;
        }
    }

    /**
     * 检查当前用户是否有查看指定类型联系人的权限
     *
     * @param companyId
     * @param userId    当前用户id
     * @param mtype     联系人类型
     * @return 返回 True False 是否有权限
     */
    public boolean checkMemberDisplayRangeByMtype(String companyId, String userId, Integer mtype) {
        CheckDisplayRangePermissionByMemberTypeRequest.Builder builder = CheckDisplayRangePermissionByMemberTypeRequest.newBuilder();
        MemberTypeEnum.MemberType memberType = MemberTypeEnum.MemberType.forNumber(mtype);
        builder.setOrgId(companyId).setUserId(userId).setMemberType(memberType);
        try {
            CheckDisplayRangePermissionResponse response = stub.checkDisplayRangePermissionByMemberType(builder.build());
            if (Objects.isNull(response) || response.getStatus().getCodeValue() != 0) {
                log.error("[survey] checkDisplayRangePermissionByMemberType, companyId = {},  userId = {}, mtype = {}, Error; ErrorMsg: {}", companyId, userId, mtype, response);
                return false;
            }
            return response.getValid();
        } catch (Exception e) {
            log.error("[survey] ex checkDisplayRangePermissionByMemberType, companyId = {},  userId = {}, mtype = {}, Error; ErrorMsg: {}", companyId, userId, mtype, e);
            return false;
        }
    }
}
